<?php
//https://packagist.org/packages/spatie/async
require '../vendor/autoload.php';

use Spatie\Async\Pool;

$results = [];

function start()
{
    $start = microtime(true);
    $pool = Pool::create();

    foreach (range(1, 20) as $i) {
        $pool[] = async(function () use ($i) {
            return file_get_contents("http://127.0.0.1:9501/test/slow_api?r=" . $i);
        })->then(function ($output) use ($i) {
            global $results;
            $results[$i] = $output;
        });
    }

    await($pool);
    echo "...done in " . (microtime(true) - $start) . PHP_EOL;
}

function start2()
{
    $start = microtime(true);
    $pool = Pool::create();

    foreach (range(20, 40) as $i) {
        $pool->add(function () use ($i) {
            return file_get_contents("http://127.0.0.1:9501/test/slow_api?r=" . $i);
        })->then(function ($output) use ($i) {
            global $results;
            $results[$i] = $output;
        })->catch(function (Throwable $exception) {
            // Handle exception
        });
    }

    $pool->wait();
    echo "...done in " . (microtime(true) - $start) . PHP_EOL;
}

start();
start2();

var_dump($results);